package com.weakteam.orderonline.adminconsole.gwt.client.widget;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.HasValueChangeHandlers;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.*;
import com.weakteam.orderonline.adminconsole.gwt.client.domain.Goods;
import com.weakteam.orderonline.adminconsole.gwt.client.util.ConsoleLog;
import com.weakteam.orderonline.adminconsole.gwt.client.util.WebContext;
import com.weakteam.orderonline.adminconsole.gwt.client.util.uploader.drop.DropHandler;
import com.weakteam.orderonline.adminconsole.gwt.client.util.uploader.file.*;


/**
 * Created by Max on 08.04.2014 for OrderOnline.
 */
public class MenuGoodsPopup extends DialogBox implements HasValueChangeHandlers<Goods> {

    interface MenuPopupUiBinder extends UiBinder<Widget, MenuGoodsPopup> { }
    private static MenuPopupUiBinder uiBinder = GWT.create(MenuPopupUiBinder.class);

    @UiField  protected TextBox nameInput;
    @UiField  protected FlowPanel imageContainer;
    @UiField  protected Image goodsImage;
    private HTML imageGlass;
    private boolean glassPrevent = false;
    private FileUpload fileUpload;
    @UiField  protected TextArea descriptionInput;
    @UiField  protected TextBox priceInput;
    @UiField  protected Button cancelButton;
    @UiField  protected Button approveButton;
    private Goods goods;

    private native void clickOnDomElement(Element elem) /*-{
        elem.click();
    }-*/;
    private native File getInputFile (Element elem) /*-{
        return elem.files[0];
    }-*/;

    public MenuGoodsPopup(Goods goods) {
        setWidget(uiBinder.createAndBindUi(this));
        this.setAnimationEnabled(true);
        this.setGlassEnabled(true);
        this.addStyleName("menu-popup");
        this.imageGlass = new HTML("<div class=\"plus\">+</div>" +
                                   "<div class=\"hint\">Перетащите<br />" +
                                   "сюда картинку</div>");
        this.imageGlass.setStyleName("image-glass");
        this.fileUpload = new FileUpload();
        this.fileUpload.setVisible(false);
        this.fileUpload.getElement().setPropertyString("accept","image/gif, image/jpeg");
        this.imageContainer.add(this.goodsImage);
        this.imageContainer.add(this.fileUpload);
        DropHandler imageDropHandler = new DropHandler(this.goodsImage);
        // add handlers
        this.goodsImage.addMouseOverHandler(new MouseOverHandler() {
            @Override
            public void onMouseOver(MouseOverEvent event) {
                if (!glassPrevent) {
                    imageContainer.add(imageGlass);
                }
            }
        });
        this.goodsImage.addMouseOutHandler(new MouseOutHandler() {
            @Override
            public void onMouseOut(MouseOutEvent event) {
                glassPrevent = false;
            }
        });
        this.imageGlass.addMouseOutHandler(new MouseOutHandler() {
            @Override
            public void onMouseOut(MouseOutEvent event) {
                imageContainer.remove(imageGlass);
                glassPrevent = false;
            }
        });
        this.goodsImage.addDragEnterHandler(new DragEnterHandler() {
            @Override
            public void onDragEnter(DragEnterEvent event) {
                glassPrevent = true;
                goodsImage.addStyleName("drop-available");
            }
        });
        this.goodsImage.addDragLeaveHandler(new DragLeaveHandler() {
            @Override
            public void onDragLeave(DragLeaveEvent event) {
                glassPrevent = false;
                goodsImage.removeStyleName("drop-available");
            }
        });
        imageDropHandler.addFileEventHandler(new FileEvent.FileEventHandler() {
            @Override
            public void onFiles(FileEvent event) {
                goodsImage.removeStyleName("drop-available");
                File file = event.getFiles().get(0);
                validateUploadImageFile(file);
                uploadImageFile(file);
            }
        });
        this.imageGlass.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                clickOnDomElement(fileUpload.getElement());
            }
        });
        this.fileUpload.addChangeHandler(new ChangeHandler() {
            @Override
            public void onChange(ChangeEvent event) {
                ConsoleLog.getInstance().debug(fileUpload.getFilename());
                File file = getInputFile(fileUpload.getElement());
                validateUploadImageFile(file);
                uploadImageFile(file);
            }
        });
        this.cancelButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                MenuGoodsPopup.this.hide();
            }
        });
        this.approveButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                ValueChangeEvent.fire(MenuGoodsPopup.this, getInputGoods());
                MenuGoodsPopup.this.hide();
            }
        });
        //
        this.goods = goods;
        String name = goods.getName();
        if (name==null) {
            name="";
            this.setText("Добавление товара");
        } else {
            this.setText("Редактирование товара");
        }
        this.nameInput.setText(name);
        this.goodsImage.setUrl(FileUtil.getImageURL(goods.getImage()));
        this.goodsImage.setAltText(goods.getImage());
        this.descriptionInput.setText(goods.getDescription());
        this.priceInput.setText(goods.getPrice().toString());
        // show
        this.center();
        this.show();

    }

    @Override
    public HandlerRegistration addValueChangeHandler(ValueChangeHandler<Goods> handler) {
        return super.addHandler(handler, ValueChangeEvent.getType());
    }

    private Goods getInputGoods() {
        goods.setName(this.nameInput.getText());
        goods.setImage(goodsImage.getAltText());
        goods.setDescription(this.descriptionInput.getText());
        goods.setPrice(Double.valueOf(this.priceInput.getText()));
        //TODO pre validate input
        return this.goods;
    }

    private void validateUploadImageFile(File file) {
        //TODO pre validate upload image
    }

    private void uploadImageFile(final File file) {
        String url = WebContext.getInstance().getRootContext() + "uploadImage?name=" + file.getFileName();
        FileUploader fileUploader = new FileUploader();
        fileUploader.addUploadHandler(new UploadHandler() {
            @Override
            public void onUploadProgress(Float percentage) {
                ConsoleLog.getInstance().debug("completed: " + percentage);
            }
            @Override
            public void onUploadCompleted(String savedFileName) {
                ConsoleLog.getInstance().debug("uploaded completed new fileName:" + savedFileName);
                goodsImage.setUrl(FileUtil.getImageURL(savedFileName));
                goodsImage.setAltText(savedFileName);
            }
            @Override
            public void onUploadError() {
                ConsoleLog.getInstance().debug("upload error");
            }
        });
        fileUploader.upload(file, url);
    }

}
